<template>
  <div>
    <el-card class="box-card">
      <div class="query-box">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="用户名">
            <el-input v-model="formInline.username" placeholder="请输入用户名" clearable></el-input>
          </el-form-item>
            <el-select v-model="formInline.taskType" placeholder="请选择" clearable>
              <div class="order-type-names-select-box" v-for="(item,index) in orderTypeNames" :key="index">
                <el-option :label="`${item}`" :value="item"></el-option>
              </div>
            </el-select>

          <el-form-item>
            <el-button type="primary" @click="getUserDataList">查询</el-button>
          </el-form-item>

          <el-form-item>
            <el-switch class="switch_box" v-model="successUser" @change="!successUser" active-text="仅查看成功做单用户"/>
          </el-form-item>
        </el-form>
      </div>

      <div class="operation-box">
        <el-button type="primary" @click="dialogFormVisible = true">新增代理</el-button>
        <el-button type="primary" @click="exportTextareaData">导出成功文本</el-button>

        <el-button type="primary" @click="exportSuccessData">下载成功数据</el-button>
        <el-button type="primary" @click="exportFailureData">导出失败数据</el-button>
        <el-button type="primary" @click="cleanOrdersRecord"  v-if="$store.getters.getUser.username=='admin'">清除做单记录</el-button>
      </div>

      <div class="task-list-box">
        <template>
          <el-table border :data="list" style="width: 100%">
            <el-table-column label="序号" type="index" width="auto">
            </el-table-column>
            <el-table-column label="用户名" width="auto">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.username }}</span>
              </template>
            </el-table-column>
            <el-table-column label="成功数量" width="auto">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.successNum }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="auto">
              <template slot-scope="scope">
                <el-button size="mini" @click="handleDetail(scope.row.id)">查看
                </el-button>
                <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <el-pagination
            :total="total"
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[5, 10, 20, 30, 50]"
            :pager-count="5"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            background
            layout="total, sizes, prev, pager, next">
          </el-pagination>
        </template>
      </div>
    </el-card>

    <el-dialog title="新增代理" :visible.sync="dialogFormVisible" class="new-broker-box">
      <el-form :model="form" class="new-broker-form-box">
        <el-form-item  class="username-box" label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off" clearable/>
        </el-form-item>
        <el-form-item class="password-box" label="密码" :label-width="formLabelWidth">
          <el-input type="password" v-model="form.password" autocomplete="off" clearable/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="broker-dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addBroker">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看详情" :visible.sync="dialogTableVisible">
      <el-table :data="detail">
        <el-table-column property="typeName" label="做单类型" width="150"></el-table-column>
        <el-table-column property="count" label="成功数量" width="200"></el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog class="export-broker-textarea-box" :visible.sync="dialogTextareaVisible">
      <h2 style="text-align: left">导出报表</h2><br><br>
      <div class="cp-textarea-box">
        <el-button type="info" class="tag-read" plain size="small" :data-clipboard-text="textarea" @click="copy">复制</el-button>
        <el-input type="textarea" :rows="25" placeholder="导出内容" v-model="textarea"/>
      </div>
    </el-dialog>
  </div>
</template>

<script>

  import Pagination from "./Pagination";
  import Clipboard from 'clipboard';

  export default {
    name: "BrokerList",
    components: {Pagination},
    data() {
      return {
        orderTypeNames: this.$store.getters.getUser.orderTypeNames||[],
        successUser: true,
        formInline: {
          username: '',
          taskType: ''
        },
        total: 12,
        pageSize: 20,
        currentPage: 1,
        pageNum: 0,
        list: [],

        dialogFormVisible: false,
        form: {
          username: '',
          password: ''
        },
        formLabelWidth: '100px',
        formInputWidth: '300px',

        dialogTableVisible: false,
        detail: [{
          typeName: '',
          count: 0,
        }],

        dialogTextareaVisible: false,
        textarea: '',
      }
    },
    watch:{
      successUser(val){
        console.log(val);
        this.getUserDataList();
      }
    },
    methods: {
      addBroker(){
        this.$http.post('/v1/users', {username: this.form.username, password: this.form.password})
        .then(res =>{
          if (res.status === 200){
            this.getUserDataList()
            this.$message({type: 'success',message: '代理添加成功!'});
            this.dialogFormVisible = false
          }
        })
        .catch(err=>{
          let {response} = err
          if (response){
            this.$message.error(response.data.message);
            return false;
          }else {
            console.log(err)
          }
        })
      },
      exportSuccessData(){
        let url = `${this.$http.defaults.baseURL}v1/users/export?status=success&taskType=${this.formInline.taskType}`;
        window.open(url)
      },
      exportFailureData(){
        let url = `${this.$http.defaults.baseURL}v1/users/export?status=fail&taskType=${this.formInline.taskType}`;
        window.open(url)
      },
      cleanOrdersRecord(){
        let taskTypeVar =this.formInline.taskType

        this.$confirm(`是否清除【${taskTypeVar||'全部'}】类型的做单记录？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {taskType: this.formInline.taskType}
          this.$http.delete('/v1/orders/clean', {params})
            .then(res =>{
              this.$message.success('做单记录清除成功')
              this.getUserDataList();
            })
            .catch(err=>{
              let {response} = err
              if (response){
                this.$message.error(response.data.message);
                return false;
              }else {
                console.log(err)
              }
            })
        }).catch(() => {
          this.$message({type: 'info', message: '已取消删除' });
        });
      },
      handleCurrentChange(val){
        console.log('val=', val)
        this.currentPage = val;
        this.getUserDataList();
      },
      handleSizeChange(val){
        console.log('val=', val)
        this.pageSize = val;
        this.getUserDataList();
      },
      handleDetail(userId){
        console.log(userId)
        this.dialogTableVisible = true
        this.$http.get('/v1/users/detail', {params: {userId}})
        .then(res => {
          console.log(res)
          if (res.status === 200){
            this.detail = res.data
            console.log(this.detail)
          }
        })
        .catch(err=>{
          let {response} = err
          if (response){
            this.$message.error(response.data.message);
            return false;
          }else {
            console.log(err)
          }
        })
      },
      handleDelete(userId){
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete(`/v1/users/${userId}`)
            .then(res => {
              this.getUserDataList()
            });
          this.$message({type: 'success',message: '删除成功!'});
        }).catch(() => this.$message({type: 'info',message: '已取消删除'}));
      },
      onSubmit() {
        console.log('submit!');
      },
      getUserDataList(){
        let params = {
          taskType: this.formInline.taskType,
          username: this.formInline.username,
          successUser: this.successUser,
          current: this.currentPage,
          pageSize: this.pageSize
        }
        this.$http.get('/v1/users/pages', {params})
        .then(res =>{
          console.log('/v1/users/pages, res= ', res)
          this.list = res.data.list
          this.total = res.data.total
          this.currentPage = res.data.pageNum
          this.pageSize = res.data.pageSize
        })
        .catch(err=>{
          let {response} = err
          if (response){
            this.$message.error(response.data.message);
            return false;
          }else {
            console.log(err)
          }
        })
      },

      open() {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      exportTextareaData(){
        this.dialogTextareaVisible = true
        this.getGroupUsers();
      },

      getGroupUsers(){
        this.$http.get('/v1/users/text/group_user')
        .then(res =>{
          console.log(res)
          if (res.status === 200){
            this.textarea = res.data;
          }
        })
        .catch(err=>{
          let {response} = err
          if (response){
            this.$message.error(response.data.message);
            return false;
          }else {
            console.log(err)
          }
        })
      },
      copy(){
        let clipboard = new Clipboard('.tag-read')
        clipboard.on('success', e => {
          this.$message({type: 'success', message: '复制成功!'});
          // 释放内存
          clipboard.destroy()
        })
        clipboard.on('error', e => {
          // 不支持复制
          console.log('该浏览器不支持自动复制')
          // 释放内存
          clipboard.destroy()
        })
      }
    },
    created() {
      this.getUserDataList();
    },

  }

</script>

<style lang="scss" scoped>
  /*@import url(); 引入公共的css类*/
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix {
    text-align: left;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }

  .box-card {
    width: auto;
  }

  .query-box {
    text-align: left;
  }

  .invite-box {
    text-align: left;
  }

  .operation-box{
    width: auto;
    text-align: left;
  }

  .new-broker-box{
    width: 78%;
  }
  .username-box{
    text-align:left;
  }
  .password-box{
    text-align:left;
  }
  .new-broker-form-box{
    padding-right: 65px;
  }
  .broker-dialog-footer{
    text-align: center;
    margin-top: -30px;
  }
  .cp-textarea-box{
    text-align: left;
  }
</style>
